package com.A1908.util;

import com.A1908.entity.Email;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

public class SendEmail {
    Properties properties = new Properties();                // 用于连接邮件服务器的参数配置（发送邮件时才需要用到）
    Session session= Session.getInstance(properties);        // 根据参数配置，创建会话对象（为了发送邮件准备的）
    MimeMessage message = new MimeMessage(session);         // 创建邮件对象

    public void sendEmail(Email email){
        properties.setProperty("mail.host","smtp.qq.com");

        properties.setProperty("mail.transport.protocol","smtp");

        properties.setProperty("mail.smtp.auth","true");

        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            Transport transport = session.getTransport();
            //连接服务器
            transport.connect("smtp.qq.com","344497521@qq.com","xhegyxscvkxmcbbc");

            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);

            //邮件发送人
            mimeMessage.setFrom(new InternetAddress("344497521@qq.com"));

            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(email.getSendAddress()));

            //邮件标题
            mimeMessage.setSubject(email.getEmailTitle());

            //邮件内容
            mimeMessage.setContent(email.getEmailText(),"text/html;charset=UTF-8");

            //发送邮件
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

            //关闭连接
            transport.close();
        } catch  (Exception e) {
            e.printStackTrace();
        }
    }
}
